﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Bll;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	public class StaffSalaryController : BaseController
	{
		private readonly SalaryHelper _helper = new SalaryHelper();

		/// <summary>
		/// 薪资计算页面
		/// </summary>
		public ActionResult CalcPage(StaffMonthlyQueryModel model)
		{
			var date = DateTime.Now.AddMonths(-1);
			if (model.Year == 0)
			{
				model.Year = date.Year;
			}
			if (model.Month == 0)
			{
				model.Month = date.Month;
			}
			if (model.Year >= date.Year && model.Month > date.Month)
			{
				return View("_Error", new ErrorViewModel {Message = string.Format("选择的月份不能晚于{0:yyyy年M月}，请重新选择！", date)});
			}

			ViewBag.QueryModel = model;
			var master = _helper.GetMaster(model.Year, model.Month);
			return master == null ? View(new StaffSalaryViewModel
			                             {
				                             Details = new List<StaffSalaryDetail>(),
				                             Summaries = new List<StaffSalarySummaryViewModel>(),
				                             SalaryParts = Db.SalaryParts.ToList()
			                             })
				       : View(_helper.GetSalaryList(model));
		}

		/// <summary>
		/// 计算统计指定月份的薪资
		/// </summary>
		public ActionResult Gather(int year, int month)
		{
			return !_helper.CalculateSalary(year, month, User) ? JError(_helper.Message) : JSuccess("统计成功！", "tab_sal_salarycalc");
		}

		public ActionResult Settle(int id)
		{
			return !_helper.Settle(id) ? JError(_helper.Message) : JSuccess("结算成功！", "tab_sal_salarycalc");
		}

		/// <summary>
		/// 我的工资
		/// </summary>
		public ActionResult MySalary(int? year)
		{
			if (User.UserType != UserTypes.Staff)
			{
				return NoAuthorization("此功能仅对集团内部员工开放！");
			}

			var date = DateTime.Now;
			var y = year ?? date.Year;
			ViewBag.Year = y;
			ViewBag.SalaryParts = Db.SalaryParts.ToList();
			return View(_helper.GetMySalaryList(User.ExtInfoId, y).ToList());
		}
	}
}